package service

import (
	"context"
	"gitee.com/crack007/goose"
	"github.com/crack007/go-im/pb"
	"github.com/crack007/go-im/src/common/model"
	"google.golang.org/grpc"
	"strconv"
	"time"
)

type slaveService struct {
}

// 从服务器启动注册
func (s *slaveService) Register(slaveRegisterModel *model.SlaveRegisterModel) error {
	masterHost := slaveRegisterModel.Master.OutIP + ":" + strconv.Itoa(int(slaveRegisterModel.Master.Port))
	goose.GetLogger().Debug("SlaveRegister-> id:%s ip:%s port:%d wsport:%d master: %s", slaveRegisterModel.Slave.Id, slaveRegisterModel.Slave.OutIP, slaveRegisterModel.Slave.Port, slaveRegisterModel.Slave.WsPort, masterHost)
	var conn *grpc.ClientConn
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	conn, err := grpc.DialContext(ctx, masterHost, grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		return err
	}
	client := pb.NewNodeServiceClient(conn)
	pbSlave := &pb.NodeInfo{}
	pbSlave.Id = slaveRegisterModel.Slave.Id
	pbSlave.Port = uint32(slaveRegisterModel.Slave.Port)
	pbSlave.Ip = slaveRegisterModel.Slave.OutIP
	pbSlave.WsPort = uint32(slaveRegisterModel.Slave.WsPort)
	_, err = client.OnConnectNode(ctx, pbSlave)
	return err
}
